package link;

import java.util.List;

/**
 * @author zhangguisong
 * @date 2022-10-25 16:15
 */
public class SingleLinkedList<E> {
    transient int size;
    transient Node<E> head;
    transient Node<E> tail;

    class Node<E> {
        private E value;
        private Node<E> next;

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }

    /**
     * 尾插法
     *
     * @author zhangguisong
     * @date 2022-10-25 16:29
     */
    public boolean add(E e) {
        Node<E> newNode = new Node(e, null);
        Node<E> l = tail;
        tail = newNode;
        if (l == null) {
            head = newNode;
        } else {
            l.next = newNode;
        }
        size++;
        return true;
    }

    /**
     * 根据值进行删除
     *
     * @author zhangguisong
     * @date 2022-10-25 16:52
     */
    public boolean remove(E e) {
        Node<E> node = head;
        Node<E> temp = null;
        while (node != null) {
            if (node.value == e) {
                // e = head.value
                if (node == head) {
                    head = node.next;
                } else if (node == tail) {
                    tail = temp;
                    temp.next = null;
                } else {
                    temp.next = node.next;
                }
                size--;
                return true;
            }
            temp = node;
            node = node.next;
        }
        return false;
    }

    public E get(int i) {
        if (i >= size || i < 0) {
            return null;
        }
        Node<E> node = head;
        int j = 0;
        while (node != null && j < i) {
            j++;
            node = node.next;
        }
        return node.value;
    }

    public boolean contains(E e) {
        Node<E> node = head;
        while (node != null) {
            if (node.value.equals(e))
                return true;
            node = node.next;
        }
        return false;
    }

    public void foo() {
        Node<E> node = head;
        while (node != null) {
            System.out.println(node.value);
            node = node.next;
        }
    }

    public static void main(String[] args) {
        SingleLinkedList<String> sl = new SingleLinkedList<>();
        sl.add("Z");
        sl.add("G");
        sl.add("S");
        sl.foo();
        sl.remove("S");
        sl.foo();
        String v = sl.get(0);
        System.out.println("0:" + v);
        System.out.println("1:" + sl.get(1));
        System.out.println(sl.contains("z"));
        System.out.println(sl.contains("Z"));

    }
}
